<template>
  <div class="app-container">
    <el-form
      ref="elForm"
      :model="formData"
      :disabled="$route.query.isInfo"
      :rules="rules"
      size="medium"
      label-width="100px"
    >
      <h2 style="text-align: center">物资回收</h2>
      <h4 class="form-header h4">基本信息</h4>
      <el-row :gutter="15">
        <!-- <el-col :span="12">
          <el-form-item label="回收编号" prop="retrieveNo">
            <el-input
              v-model="formData.retrieveNo"
              placeholder="保存后自动生成"
              :disabled="true"
              clearable
              :style="{ width: '100%' }"
            ></el-input>
          </el-form-item>
        </el-col>-->
        <el-col :span="12">
          <el-form-item label="回收人" prop="userId">
            <UserDialog placeholder="请选择回收人" disabled v-model="formData.userId"></UserDialog>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="回收时间" prop="retrieveDate">
            <el-date-picker
              v-model="formData.retrieveDate"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :style="{ width: '100%' }"
              placeholder="请选择回收时间"
              clearable
            ></el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>
      <h4 class="form-header h4">附件信息</h4>
      <el-form-item label prop="oss">
        <FileUploadBase :isDelete="!$route.query.isInfo" v-model="formData.oss"></FileUploadBase>
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入多行文本备注"
          :autosize="{ minRows: 4, maxRows: 4 }"
          :style="{ width: '100%' }"
        ></el-input>
      </el-form-item>

      <h4 class="form-header h4">
        明细
        <el-button type="primary" plain size="mini" @click="handleAdd">增行</el-button>
        <el-button type="danger" plain size="mini" @click="handleDele">删行</el-button>
      </h4>
      <el-table :data="formData.relatedGoodsList" :border="true" style="width: 100%">
        <el-table-column label="序号" type="index" align="center" />
        <el-table-column label="用品名称" align="center">
          <template slot-scope="scope">
            <el-form-item
              label-width="0"
              :prop="`relatedGoodsList.${scope.$index}.goodsName`"
              :rules="rules.goodsName"
            >
              <div @click="onSelectNextUsers(scope.row, scope.$index)">
                <el-input   v-model="scope.row.goodsName" readonly placeholder="选择用品名称"></el-input>
              </div>
            </el-form-item>
          </template>
        </el-table-column>
        <!-- <el-table-column label="重点物资编号" width="250" prop="price" align="center">
          <template slot-scope="scope">
            <el-form>
              <el-form-item label-width="0">
                <el-select v-model="scope.row.nameString" multiple collapse-tags :disabled="false">
                  <el-option
                    disabled
                    v-for="dict in scope.row.nameString"
                    :key="dict"
                    :label="dict"
                    :value="dict"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>-->
        <el-table-column label="用品类别" prop="typeName" align="center"></el-table-column>
        <el-table-column label="单位" prop="unit" align="center"></el-table-column>
        <el-table-column label="规格" prop="spec" align="center"></el-table-column>
        <!-- <el-table-column label="单价" prop="price" align="center"></el-table-column> -->
        <el-table-column label="回收数量" align="center">
          <template slot-scope="scope">
            <el-form-item
              label-width="0"
              :prop="`relatedGoodsList.${scope.$index}.outCount`"
              :rules="rules.outCount"
            >
              <el-input @input="scrapNumIpt($event,scope.row)" v-model="scope.row.outCount" placeholder="请输入回收数量"></el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <!-- <el-table-column label="金额" prop="money" align="center"></el-table-column> -->
      </el-table>
      <el-col :span="24">
        <el-form-item label-width="0" style="text-align: center; margin-top: 30px">
          <el-button v-if="!$route.query.isInfo" type="primary" @click="submitForm">提交</el-button>
          <el-button :disabled="false" @click="resetForm">返回</el-button>
        </el-form-item>
      </el-col>
    </el-form>
    <el-dialog :title="userData.title" :visible.sync="userData.open" width="60%" append-to-body>
      <el-row type="flex" :gutter="20">
        <!--部门数据-->
        <el-col :span="5">
          <el-card shadow="never" style="height: 100%">
            <div slot="header">
              <span>分类列表</span>
            </div>
            <div class="head-container">
              <el-input
                v-model="deptName"
                placeholder="请输入分类列表"
                clearable
                size="small"
                prefix-icon="el-icon-search"
              />
              <el-tree
                :data="dict.type.sys_goods_type"
                :props="deptProps"
                :expand-on-click-node="false"
                :filter-node-method="filterNode"
                ref="tree"
                default-expand-all
                @node-click="handleNodeClick"
              />
            </div>
          </el-card>
        </el-col>
        <el-col :span="18">
          <el-table
            ref="userTable"
            :key="userData.type"
            height="500"
            v-loading="userLoading"
            :data="goodsList"
            highlight-current-row
            @row-click="changeCurrentUser"
          >
            <el-table-column type="index" align="center" label="序号" />

            <el-table-column label="名称" align="center" prop="goodsName" />
            <el-table-column label="单位" align="center" prop="unit" />
            <el-table-column label="规格" align="center" prop="spec" />
            <el-table-column label="是否重点" align="center" prop="hasObj" />
          </el-table>
          <pagination
            :total="total"
            :page.sync="queryParams1.pageNum"
            :limit.sync="queryParams1.pageSize"
            @pagination="getListGoods"
          />
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="userData.open = false">取 消</el-button>
        <el-button :disabled="$route.query.isInfo" type="primary" @click="submitUserData">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="重点物资分配" :visible.sync="openObj" width="60%">
      <el-table
        ref="userTable2"
        v-loading="userLoading"
        :data="ObjBoList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />

        <el-table-column label="编号" align="center" prop="goodsObjCode" />

        <el-table-column label="名称" align="center" prop="goodsName" />
        <el-table-column label="拥有者" align="center" prop="ownerName" />
        <el-table-column label="是否报废" align="center" prop="objStatus">
          <template slot-scope="scope">{{ scope.row.objStatus == 1 ? "是" : "否" }}</template>
        </el-table-column>
        <el-table-column label="是否发放" align="center" prop="objStatus">
          <template slot-scope="scope">{{ scope.row.ownerStatus == 1 ? "是" : "否" }}</template>
        </el-table-column>
      </el-table>
      <pagination
        :total="totalObj"
        :page.sync="queryParamsObj.pageNum"
        :limit.sync="queryParamsObj.pageSize"
        @pagination="objListGet"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="openObj = false">取 消</el-button>
        <el-button :disabled="$route.query.isInfo" type="primary" @click="submitObj">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import store from "@/store";
import { userSelect, deptTreeSelect } from "@/api/system/user.js";
import { listGoods, objList,detailQueryPageList } from "@/api/finance/goods.js";
import {
  retrieveAdd,
  updategretrieve,
  retrieveInfo
} from "@/api/finance/retrieve.js";

export default {
  components: {},
  dicts: ["sys_goods_type", "sys_goodsout_type", "sys_goodsget_type"],

  props: [],
  data() {
    return {
      openObj: false,
      deptProps: {
        children: "children",
        label: "label"
      },
      userData: {
        title: "查找物资",
        type: "",
        open: false
      },
      userLoading: false,
      total: 0,
      goodsList: [],

      currentRow: "",
      currentIndex: 0,
      deptOptions: [],
      // 部门名称
      deptName: undefined,
      queryParams1: {
        pageNum: 1,
        pageSize: 10
      },
      totalObj: 0,
      queryParamsObj: {
        pageNum: 1,
        pageSize: 10
      },
      ObjBoList: [],
      userList: [],
      formData: {
        retrieveNo: undefined,
        retrieveDate: null,
        userId: undefined,
        mainId: undefined,
        userTypeValue: undefined,

        relatedGoodsList: [
          {
            goodsName: "",
            typeName: "",
            spec: "",
            unit: "",
            price: "",
            outCount: "",
            money: "",
            currentStock: "",
            detailList: []
          }
        ]
      },
      detailList: [],
      detailObj: [],

      operUserIdOptions: [],
      currentUserId: null,
      rules: {
        goodsName: [
          {
            required: true,
            message: "请选择用品名称",
            trigger: "change"
          }
        ],
        outCount: [
          {
            required: true,
            message: "请输入回收数量",
            trigger: "blur"
          }
        ],
        info: [
          {
            required: true,
            message: "请输入费用详细",
            trigger: "blur"
          }
        ],
        remark: [
          {
            required: true,
            message: "请输入多行文本备注",
            trigger: "blur"
          }
        ],
        oss: [
          {
            required: true,
            message: "附件不能为空",
            trigger: "change"
          }
        ],
        retrieveNo: [],
        retrieveDate: [
          {
            required: true,
            message: "请选择入库日期",
            trigger: "change"
          }
        ],
        userId: [
          {
            required: true,
            message: "请选择领取人",
            trigger: "change"
          }
        ],
        mainId: [
          {
            required: true,
            message: "请选择实际领取人",
            trigger: "change"
          }
        ],
        userTypeValue: [
          {
            required: true,
            message: "请选择使用类型",
            trigger: "change"
          }
        ],
        getMethodValue: [
          {
            required: true,
            message: "请选择领取方式",
            trigger: "change"
          }
        ]
      }
    };
  },
  computed: {},
  created() {
    this.userSelect();
    if (this.$route.query.isEdit || this.$route.query.isInfo) {
      this.getinfoFee();
    }
    this.formData.userId = this.$store.state.user.id;
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1; // 月份从0开始，所以要加1
    const day = today.getDate();
    this.formData.getUserId = this.$store.state.user.id;
    this.formData.retrieveDate = `${year}-${month}-${day}`;
  },
  watch: {
    "formData.relatedGoodsList": {
      deep: true,
      handler: function(newVal, oldVal) {
        let num = 0;
        newVal.forEach(i => {
          let p =
            (!isNaN(Number(i.outCount)) ? Number(i.outCount) : 0) * i.price;
          i.money = (Math.round(p * 100) * 1000) / 1000 / 100;
        });
      }
    },
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },

  mounted() {
    this.getDeptTree();
  },
  methods: {
    handleSelectionChange(selection) {
      this.detailObj = selection;
    },
    selectEnable(row, rowIndex) {
      return row.objStatus == 0;
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
      });
    },
    onSelectNextUsers(row, index) {
      this.currentIndex = index;
      this.currentUserId = row.goodsId;

      this.onSelectUsers("查找物资", "next");
    },
    scrapNumIpt(e,l){
      console.log(e,l);
      if (Number(e)>Number(l.remainCount)) {
        this.$modal.msgError("废弃数量不得大于当前领用数量！");
        return false;
      }
    },
    onSelectUsers(title, type) {
      this.userData.title = title;
      this.userData.type = type;
      this.getListGoods();
      this.userData.open = true;
    },

    getListGoods() {
      this.userLoading = true;
      // this.queryParams1.effectStatus = 1;
      detailQueryPageList(this.queryParams1).then(
        response => {
          this.goodsList = response.rows;
          this.total = response.total;
          this.currentRow = this.goodsList.find(
            k => k.goodsId === this.currentUserId
          );
          this.toggleSelection(this.currentRow);
          this.userLoading = false;
        }
      );
    },
    objListGet() {
      this.queryParamsObj.ownerStatus = 1;
      objList(this.queryParamsObj).then(response => {
        this.ObjBoList = response.rows;
        this.totalObj = response.total;
        this.$nextTick(() => {
          this.formData.relatedGoodsList[this.currentIndex].detailList.forEach(
            item => {
              let row = this.ObjBoList.find(
                k => k.goodsObjId === item.goodsObjId
              );
              console.log(row);
              this.$refs.userTable2.toggleRowSelection(row);
            }
          );
        });
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams1.typeValue = data.value;
      this.getListGoods();
    },
    changeCurrentUser(val) {
      this.currentUserId = val.goodsId;
      if (val.hasObj == 1) {
        this.objListGet();
        this.detailObj = [];
        this.detailList = [];
        this.openObj = true;

        if (
          this.formData.relatedGoodsList[this.currentIndex].detailList.length
        ) {
          this.detailObj = this.formData.relatedGoodsList[
            this.currentIndex
          ].detailList;
          this.detailList = this.formData.relatedGoodsList[
            this.currentIndex
          ].detailList;
        }
      }
    },
    toggleSelection(selection) {
      if (selection) {
        this.$nextTick(() => {
          this.$refs.userTable.setCurrentRow(this.currentRow);
        });
      } else {
        this.$nextTick(() => {
          this.$refs.userTable.clearSelection();
        });
      }
    },
    submitUserData() {
      if (!this.currentUserId) {
        this.$modal.msgError("请选择物资");
        return false;
      }
      //  获取当前行数据
      this.currentRow = this.goodsList.find(
        k => k.goodsId === this.currentUserId
      );
      if (this.currentRow.hasObj == 1) {
        console.log(this.detailList.length);
        if (this.detailList.length) {
          this.$set(this.formData.relatedGoodsList, this.currentIndex, {
            ...this.currentRow
          });
          this.$set(
            this.formData.relatedGoodsList[this.currentIndex],
            "detailList",
            this.detailList
          );
          this.userData.open = false;
          let name = this.detailList.map(i => i.goodsObjCode);
          this.$set(
            this.formData.relatedGoodsList[this.currentIndex],
            "nameString",
            name
          );
        } else {
          this.$modal.msgError("重点物资请选择具体对象");
          this.objListGet();
          this.detailList = [];
          this.detailObj = [];

          this.openObj = true;
          return false;
        }
      } else {
        this.$set(this.formData.relatedGoodsList, this.currentIndex, {
          ...this.currentRow
        });
        this.userData.open = false;
      }
    },
    submitObj() {
      if (!this.detailObj.length) {
        this.$modal.msgError("请选择物资对象");
        return false;
      }
      this.detailList = this.detailObj;
      // 赋值

      this.openObj = false;
    },

    userSelect() {
      userSelect().then(response => {
        this.operUserIdOptions = response.data;
      });
    },
    handleAdd() {
      this.formData.relatedGoodsList.push({
        goodsName: "",
        typeName: "",
        spec: "",
        unit: "",
        price: "",
        outCount: "",
        money: "",
        currentStock: "",
        detailList: []
      });
    },
    handleDele() {
      if (this.formData.relatedGoodsList.length == 1) return;
      this.formData.relatedGoodsList.pop();
    },
    getinfoFee() {
      retrieveInfo(this.$route.query.id).then(response => {
        this.formData = response.data;
        this.formData.relatedGoodsList.forEach(e => {
          let name = e.detailList.map(i => i.goodsObjCode);
          this.$set(e, "nameString", name);
        });
      });
    },
    submitForm() {
      this.$refs["elForm"].validate(valid => {
        if (valid) {
          let query = JSON.parse(JSON.stringify(this.formData));
          query.userName = this.operUserIdOptions.find(
            i => i.userId === query.userId
          ).nickName;
          if (this.formData.goodsRetrieveId != undefined) {
            updategretrieve(query).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.resetForm();
            });
          } else {
            retrieveAdd(query).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.resetForm();
            });
          }
        }
      });
    },
    resetForm() {
      const obj = { path: "./retrieve" };
      this.$tab.closeOpenPage(obj);
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-tag.el-tag--info .el-tag__close {
  display: none !important;
}
</style>
